package com.quicks.beauty.server.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.quicks.beauty.core.dao.UserBillMapper;
import com.quicks.beauty.core.dao.WxUserMapper;
import com.quicks.beauty.core.entity.UserBill;
import com.quicks.beauty.core.entity.UserBillExample;
import com.quicks.beauty.core.entity.UserOrder;
import com.quicks.beauty.core.entity.WxUser;
import com.quicks.beauty.core.utils.CommonUtils;
import com.quicks.beauty.core.utils.LocalDateTimeUtils;
import com.quicks.beauty.core.vo.UserBillVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.jaxb.SpringDataJaxb;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UserBillService {

    @Autowired
    private UserBillMapper userBillMapper;

    @Autowired
    private WxUserMapper wxUserMapper;

    public int insertBill(String userId, String imagePath, String billId) {

        UserBillExample example = new UserBillExample();
        example.createCriteria().andUserIdEqualTo(userId)
                .andCreateTimeBetween(LocalDateTimeUtils.getDayStartDate(), new Date());
        int i = userBillMapper.countByExample(example);
        if (i >= 10) {
            return 10;
        }

        UserBill bill = new UserBill();
        Date date = new Date();
        bill.setId(billId).setBillCode(CommonUtils.generateOrderNo("AD"));
        bill.setCreateBy(userId).setUserId(userId).setImageUrl(imagePath).setPoints(0);
        bill.setStates(0).setDeleted(0).setCreateTime(date).setUpdateTime(date);
        bill.setUpdateBy(userId).setCreateBy(userId).setRemark("new");
        int insert = userBillMapper.insert(bill);
        return insert;
    }

    /*
       分页获取产品数目
        */
    public List<UserBillVO> getUserBillVOs(String userId, int pageNum, int pageSize) throws Exception {
        PageHelper.startPage(pageNum, pageSize, true);
        Page<UserBillVO> pager = userBillMapper.getUserBillVOs(userId);
        List<UserBillVO> result = pager.getResult();
        if (!result.isEmpty()) {
            result.forEach(st -> {
                int states = st.getStates();
                if (states == 0) {
                    st.setStatus("等待审核");
                    st.setReason("");
                } else if (states == 1) {
                    st.setStatus("审核不通过");
                } else if (states == 2) {
                    st.setStatus("审核通过");
                    st.setReason("美颜值 + " + st.getPoints());
                }
            });
        }
        return result;
    }

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendMailMsg(String userId, String orderId) {

        UserBill bill = userBillMapper.selectByPrimaryKey(orderId);

        WxUser wxUser = wxUserMapper.selectByPrimaryKey(userId);


        String nickName = wxUser.getNickName();
        Date createTime = bill.getCreateTime();
        String imageUrl = bill.getImageUrl();
        String billCode = bill.getBillCode();
        String subject = nickName+" 提交凭证审核单";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String format = simpleDateFormat.format(createTime);
        String end = "<html lang=\"en\"><body>快美直通车 提醒您：<br><p  style='text-indent: 2em;'>"+nickName+" 于 "+format+"提交凭证审核单，单号为:"+billCode+" 凭证图片为:"+"<img src='"+imageUrl+"'></p></body></html>";
        try {
            sendHtmlMail(subject,end);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

    public void sendMailMsg1(String userId, String orderId) {

        // UserBill bill = userBillMapper.selectByPrimaryKey(orderId);
        Map<String,Object> userOrder = userBillMapper.findOrderById(orderId);
        WxUser wxUser = wxUserMapper.selectByPrimaryKey(userId);
        String productName = (String)userOrder.get("productName");
        Integer kinds = (Integer)userOrder.get("kinds");
        Integer states = (Integer) userOrder.get("states") ;
        String leixing = "";
        if(kinds == 0){
            leixing ="医疗服务";
        }else if(kinds == 1){
            leixing ="普通礼品";
        }else if(kinds == 2){
            leixing ="爱帽饰品";
        }
        Integer prodNum =(Integer)userOrder.get("prodNumber") ;
        String expressCompany = (String)userOrder.get("expressCompany") ;
        String mobile = (String)userOrder.get("mobile");
        if(states ==0){
            if(expressCompany ==null){
                expressCompany ="";
            }
        }else if(states ==2){
            expressCompany ="到店自取";
        }else if(states ==4){
            expressCompany ="到店体验";
        }

        String createBy = (String)userOrder.get("createBy") ;
        // ua.province as province,ua.city as city ,ua.town as town, ua.others as others,u.mobile as mobile
        String province = (String)userOrder.get("province") ;
        if(province == null){
            province = "";
        }
        String city = (String)userOrder.get("city") ;
        if(city == null){
            city = "";
        }
        String town = (String)userOrder.get("town") ;
        if(town == null){
            town = "";
        }
        String others = (String)userOrder.get("others") ;
        if(others == null){
            others = "";
        }
        String address = province+city+town+others;

        String username = (String)userOrder.get("username") ;
        String  userName = "";
        if(states ==0){
            userName =username;
        }else if(states == 2 || states == 4){
            userName = createBy;
        }
        String nickName = wxUser.getNickName();
        Date createTime = (Date)userOrder.get("createTime");
        //String imageUrl = (String)userOrder.get("urls");
        String orderCodes = (String)userOrder.get("orderCodes");
        Integer unitPoints = (Integer) userOrder.get("unitPoints");
        BigDecimal money = (BigDecimal)userOrder.get("money");
        Integer points = (Integer)userOrder.get("points");
        String subject = nickName+" 提交兑换订单";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String format = simpleDateFormat.format(createTime);
        // String end = "<html lang=\"en\"><body>快美直通车 提醒您：<br><p  style='text-indent: 2em;'>"+nickName+" 于 "+format+"提交兑换订单，单号为:"+orderCodes+" </p></body></html>";
        String end = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><title>Title</title><style>table,table td { padding: 1rem 2rem; border: 1px dashed #6D8DFE; border-collapse: collapse; text-align: center;}</style></head><body>";
        end +="快美直通车 提醒您：<br><p style='text-indent: 2em;'>"+nickName+" 于 "+format+"提交兑换订单</p><br>";
       // end +="<br><table><thead><tr><td>昵称</td><td>订单号</td><td>礼品</td><td>礼品类型</td><td>数量</td><td>配送方式</td><td>预约人/收货人</td><td>详细</td></tr></thead>";
       // end +="<tbody><tr><td>"+nickName+"</td><td>"+orderCodes+"</td><td>"+productName+"</td><td>"+leixing+"</td><td>"+prodNum+"</td><td>"+expressCompany+"</td><td>"+userName+"</td><td>"+address+"</td></tr></tbody></table></body></html>";
        end += "<table><tr><td>昵称</td><td>"+nickName+"</td></tr><tr><td>订单号</td><td>"+orderCodes+"</td></tr><tr><td>礼品</td><td>"+productName+"</td></tr><tr><td>礼品积分</td><td>"+unitPoints+"</td></tr><tr><td>礼品类型</td><td>"+leixing+"</td>";
        end +="</tr><tr><td>数量</td><td>"+prodNum+"</td></tr><tr><td>订单金额/积分</td><td>"+"￥"+money+"+"+points+"</td></tr><tr><td>手机</td><td>"+mobile+"</td></tr><tr><td>配送方式</td><td>"+expressCompany+"</td></tr><tr><td>预约人/收件人</td><td>"+userName+"</td></tr><tr><td>详细</td><td>"+address+"</td></tr></table>";
        try {
            sendHtmlMail(subject,end);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }


    public void sendHtmlMail(String subject, String content) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom("why627070233@163.com");
        String to3 = "xiaojian.sun@kuaiyou.com";
        String to2 = "wenwen.li@kuaiyou.com";
        String to1 = "jiadong.li@kuaiyou.com";
        //正式才有的
      //  String to0 = "haixia.xu@kuaiyou.com";
        String[] arrs = {to3,to2,to1};
        helper.setTo(arrs);
        helper.setSubject(subject);
        helper.setText(content, true);
        javaMailSender.send(message);
    }

}
